package org.codefinger.json.parser.deserializer;

import org.codefinger.json.parser.JSONArrayDeserializer;
import org.codefinger.json.parser.JSONLexer;
import org.codefinger.json.parser.JSONObjectDeserializer;

public class ObjectDeserializerForPojo implements JSONObjectDeserializer {

	private PojoDeserializer		pojoDeserializer;

	private PojoFieldDeserializer	fieldDeserializer;

	private Object					target;

	public ObjectDeserializerForPojo(PojoDeserializer pojoDeserializer) {
		this.pojoDeserializer = pojoDeserializer;
		this.target = pojoDeserializer.newInstance();
	}

	@Override
	public JSONArrayDeserializer createArrayDeserializer() {
		return fieldDeserializer == null ? ArrayDeserializerForNull.INSTANCE : fieldDeserializer
				.createArrayDeserializer();
	}

	@Override
	public JSONObjectDeserializer createObjectDeserializer() {
		return fieldDeserializer == null ? ObjectDeserializerForNull.INSTANCE : fieldDeserializer
				.createObjectDeserializer();
	}

	@Override
	public void setFieldName(JSONLexer jsonLexer) {
		setFieldName(jsonLexer.getJSONString());
	}

	@Override
	public void setFieldName(String fieldName) {
		fieldDeserializer = pojoDeserializer.getPojoFieldDeserializerCache(fieldName);
	}

	@Override
	public void setValue(Object value) {
		if (fieldDeserializer == null) {
			return;
		}
		fieldDeserializer.setValue(target, value);
	}

	@Override
	public void setStringValue(JSONLexer jsonLexer) {
		if (fieldDeserializer == null) {
			jsonLexer.skipCurrentString();
			return;
		}
		fieldDeserializer.setStringValue(target, jsonLexer);
	}

	@Override
	public void setIntValue(String value) {
		if (fieldDeserializer == null) {
			return;
		}
		fieldDeserializer.setIntValue(target, value);
	}

	@Override
	public void setFloatValue(String value) {
		if (fieldDeserializer == null) {
			return;
		}
		fieldDeserializer.setFloatValue(target, value);
	}

	@Override
	public void setFalseValue() {
		if (fieldDeserializer == null) {
			return;
		}
		fieldDeserializer.setFalseValue(target);
	}

	@Override
	public void setTrueValue() {
		if (fieldDeserializer == null) {
			return;
		}
		fieldDeserializer.setTrueValue(target);
	}

	
	@Override
	public Object getDeserializedValue() {
		return  target;
	}

}
